<template>
  <q-layout>
    <header class="row q-pa-lg bg-grey justify-center">
      <div class="container row justify-center bg-yellow">
        <!-- 一级标题 -->
        <div class="menu text-h5 col text-center" v-for="menu in titles" :key="menu.name">
          <span>{{ menu.name }}</span>
          <!-- 二级标题 -->
          <ul class="sub-menu row justify-center bg-green">
            <li class="q-ma-lg" v-for="submenu in menu.children" :key="submenu.name" @click="clickSubmenu(submenu)">
              {{ submenu.name }}
            </li>
          </ul>
        </div>
      </div>
    </header>

  </q-layout>
</template>

<script setup>
import { ref } from "vue";
import { onMounted } from "vue";

const titles = ref([
  {
    name: "Xiaomi手机", path: "", children: [
      { name: "小米13", path: "" },
      { name: "小米13Pro", path: "" },
      { name: "小米11 青春活力版", path: "" },
    ]
  },
  {
    name: "Xiaomi手机", path: "", children: [
      { name: "sss", path: "" },
      { name: "ddd", path: "" },
      { name: "ddd ddd", path: "" },
    ]
  }
])

onMounted(() => {
  let container = document.querySelector(".container");
  let menus = document.querySelectorAll(".menu");
  let subMenus = document.querySelectorAll(".sub-menu");

  let checkedMenus = ref([]);
  setSubMenuLeaveTrans();

  // 离开 container-nav（一定离开了 menu），离开需要动画
  container.addEventListener("mouseleave", () => {
    setSubMenuLeaveTrans();
  })

  menus.forEach((menu, index) => {
    // 离开 menus[index] 但没有离开 container-nav
    menu.addEventListener("mouseleave", () => {
      subMenus[index].style = "max-height: 0px;overflow: hidden;"
      subMenus[index].style.transition = "all .5s";
    })

    menu.addEventListener("mouseenter", () => {
      checkedMenus.value[index] = true;
      subMenus[index].style = "max-height: 200px;";
      subMenus[index].style.transition = "all .5s";
    })
  })

  /* 设置所有 submenu 的过渡效果 */
  function setSubMenuLeaveTrans() {
    menus.forEach((menu, index) => {
      // 设置 css 的代码顺序不能变，否则没有过渡效果
      subMenus[index].style = "max-height: 0px;overflow: hidden;"
      subMenus[index].style.transition = "all .5s";
    })
  }
  /* 计算共有几个menu被hover过 */
  function countCheckedMenu(array) {
    return array.filter((e) => e == true).length;
  }
})

function clickSubmenu(submenu) {
  console.log(submenu.name);
}
</script>



<style scoped>
.container ul {
  padding: 0;
  margin: 0;
  list-style: none;
}

/* 包裹所有标题tab的容器 */
.container {
  position: relative;
  width: 100%;
}

/* 一级标题样式 */
.menu {
  border: 1px solid blue;
}

/* 二级标题样式 */
.sub-menu {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
}

.sub-menu {
  /* 这里不需要设置 transition */
  /* 初始化，必需 */
  max-height: 0;
  overflow: hidden;
}
</style>